import pandas as pd
import numpy as np

from uiautomation import WindowControl, MenuControl

# 绑定微信主窗口
wx = WindowControl(Name='微信')

# 切换窗口
wx.SwitchToThisWindow()
# 寻找会话控件绑定
hw = wx.ListControl(Name='会话')
filename = input("请输入文件名(包括文件格式)：")
# 指定要检测的用户名
target_user = input("请输入指定的触发用户昵称：")
# 输入密码
password = input("请输入用户的密码：")
# 话术
huashu1 = input("请输入话术1：")
huashu2 = input("请输入话术2：")
huashu3 = input("请输入话术3：")
huashu4 = input("请输入话术4：")

print("等待未读消息中请勿关闭此窗口，请勿关闭微信窗口。。。。。。。。")
# 通过pd读取数据
df = pd.read_excel(filename)

# 死循环接受消息
while True:
    # 从查找未读消息
    we = hw.TextControl(searchDepth=4)

    # 死循环维持，没有超时报错
    while not we.Exists(0):
        pass

    # 存在未读消息
    if we.Name:
        # 点击未读消息
        we.Click(simulateMove=False)

        # 读取最后一条消息
        last_msg = wx.ListControl(Name='消息').GetChildren()[-1].Name

        control = wx.ListControl(Name='消息').GetChildren()[-1].ButtonControl()

        if control.Name == target_user:
            # 判断关键字
            try:
                msg = df.loc[df['姓名'] == last_msg]

                index = msg.index.values[0]

                ar = np.array(msg).tolist()[0]

                df.iat[index, 6] = 1

                print(last_msg+"已标记")

                df.to_excel(filename, index=False, engine='openpyxl')

            except Exception:
                ar = []

            # 能够匹配到数据时
            if ar:
                # 将数据输入
                # 替换换行符号
                wx.SendKeys('账号：' + str(ar[4]), waitTime=0)
                wx.SendKeys('{Enter}', waitTime=0)
                wx.SendKeys('密码：'+password, waitTime=0)
                wx.SendKeys('{Enter}', waitTime=0)
                if huashu1:
                    wx.SendKeys(huashu1, waitTime=0)
                    wx.SendKeys('{Shift}{Enter}', waitTime=0)
                if huashu2:
                    wx.SendKeys('{Shift}{Enter}', waitTime=0)
                    wx.SendKeys(huashu2, waitTime=0)
                    wx.SendKeys('{Shift}{Enter}', waitTime=0)
                if huashu3:
                    wx.SendKeys('{Shift}{Enter}', waitTime=0)
                    wx.SendKeys(huashu3, waitTime=0)
                    wx.SendKeys('{Shift}{Enter}', waitTime=0)
                if huashu4:
                    wx.SendKeys('{Shift}{Enter}', waitTime=0)
                    wx.SendKeys(huashu4, waitTime=0)
                # 发送消息
                wx.SendKeys('{Enter}', waitTime=0)
                # 通过消息匹配检索会话栏的联系人
                wx.TextControl(SubName=target_user).RightClick()
            # 没有匹配到数据时
            else:
                notFindMsg = "找不到学生，请给我正确的姓名"
                wx.SendKeys(notFindMsg, waitTime=0)
                # 发送消息
                wx.SendKeys('{Enter}', waitTime=0)

                # 通过消息匹配检索会话栏的联系人

                wx.TextControl(SubName=notFindMsg[:5]).RightClick()

            # 匹配右击控件
            ment = MenuControl(ClassName='CMenuWnd')
            # 点击右键控件中的不显示聊天
            ment.TextControl(Name='不显示聊天').Click()
